package com.cloudeasy.search.controller;

import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.PageResult;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.search.po.Post;
import com.cloudeasy.search.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;


@RestController
@CrossOrigin
public class SearchController {
    private final PostService postService;

    @Autowired
    public SearchController(PostService postService) {
        this.postService = postService;
    }

    @GetMapping("/{page}/{size}")
    public Result<PageResult<Post>> search(@RequestParam("content") String content,
                                           @PathVariable("page") Integer page,
                                           @PathVariable("size") Integer size) {
        Page<Post> posts = postService.search(content, page, size);
        PageResult<Post> pageResult = new PageResult<>();
        pageResult.setPages((long) posts.getTotalPages())
                .setTotal(posts.getTotalElements())
                .setRecords(posts.getContent());
        return ResultUtil.success(pageResult);
    }

    @DeleteMapping("/all")
    public Result clear() {
        postService.clear();
        return ResultUtil.success();
    }
}
